import os
import sys
import stat

def force_remove_directory(path):
    """
    强力删除目录，包括只读文件，并显示进度
    """
    if not os.path.exists(path):
        print(f"路径不存在: {path}")
        return True
    
    print(f"开始扫描目录结构: {path}")
    # 先统计要删除的文件和文件夹数量
    total_items = 0
    for root, dirs, files in os.walk(path):
        total_items += len(dirs) + len(files)
    print(f"总共需要删除 {total_items} 个项目")
    
    deleted_items = 0
    
    def on_rm_error(func, path, exc_info):
        """
        处理删除过程中遇到的错误
        """
        # 修改文件权限并再次尝试删除
        os.chmod(path, stat.S_IWRITE)
        try:
            func(path)
        except Exception as e:
            print(f"警告: 无法删除 {path}: {e}")
    
    # 使用自定义的删除逻辑显示进度
    for root, dirs, files in os.walk(path, topdown=False):
        # 先删除文件
        for name in files:
            file_path = os.path.join(root, name)
            try:
                os.chmod(file_path, stat.S_IWRITE)
                os.remove(file_path)
                deleted_items += 1
                if deleted_items % 100 == 0 or deleted_items == total_items:
                    print(f"已删除 {deleted_items}/{total_items} 个项目")
            except Exception as e:
                print(f"无法删除文件 {file_path}: {e}")
        
        # 再删除空目录
        for name in dirs:
            dir_path = os.path.join(root, name)
            try:
                os.rmdir(dir_path)
                deleted_items += 1
                if deleted_items % 100 == 0 or deleted_items == total_items:
                    print(f"已删除 {deleted_items}/{total_items} 个项目")
            except Exception as e:
                print(f"无法删除目录 {dir_path}: {e}")
    
    # 最后删除根目录本身
    try:
        os.rmdir(path)
        deleted_items += 1
        print(f"已删除 {deleted_items}/{total_items} 个项目")
    except Exception as e:
        print(f"无法删除根目录 {path}: {e}")
        return False
    
    print("删除完成")
    return True

def main():
    if len(sys.argv) < 2:
        print("用法: python rm.py <目录路径>")
        sys.exit(1)
    
    target_path = sys.argv[1]
    
    if not os.path.exists(target_path):
        print(f"错误: 路径 '{target_path}' 不存在")
        sys.exit(1)
    
    # 检查是否为目录
    if not os.path.isdir(target_path):
        print(f"错误: '{target_path}' 不是一个目录")
        sys.exit(1)
    
    print(f"正在强力删除目录: {target_path}")
    
    if force_remove_directory(target_path):
        print(f"成功删除目录: {target_path}")
    else:
        print(f"删除目录失败: {target_path}")
        sys.exit(1)

if __name__ == "__main__":
    main()